import { Algorithm } from "../types"

// 数据模型定义
interface MPLPNode {
  id: any
  type: string
  attributes: Record<string, any>
}

interface MPLPEdge {
  source: any
  target: any
  type?: string
  weight?: number
  attributes: Record<string, any>
}

interface MPLPGraph {
  nodes: MPLPNode[]
  edges: MPLPEdge[]
}

// 定义时序图数据结构
interface TemporalGraph {
  nodes: MPLPNode[]
  edges: MPLPEdge[]
  timestamp: string
}

// 修改任务状态枚举
enum TaskStatus {
  PENDING = "PENDING",
  RUNNING = "RUNNING", 
  COMPLETED = "COMPLETED",
  FAILED = "FAILED"
}

// 修改接口定义以匹配后端schema
interface TSGEInputParams {
  graph_sequence: Array<{
    nodes: MPLPNode[];
    edges: MPLPEdge[];
  }>;
  embedding_dim: number;
  learning_rate: number;
  epochs: number;
  node_types?: Record<string, string>;
}

interface NodeEmbedding {
  node_id: string;
  embedding: number[];
  node_type?: string;
}

interface LinkPrediction {
  source: string;
  target: string;
  probability: number;
  time?: number;
}

interface TSGEOutputParams {
  node_embeddings: NodeEmbedding[];
  link_predictions?: LinkPrediction[];
  algorithm: string;
  parameters: Record<string, any>;
  train_loss_history?: number[];
}

interface InputParams {
  tsge_params?: TSGEInputParams;
  drpa_params?: DRPAInputParams;
  evolution_predict_params?: EvolutionPredictInputParams;
}

interface OutputParams {
  tsge_results?: TSGEOutputParams;
  drpa_results?: DRPAOutputParams;
  evolution_predict_results?: EvolutionPredictOutputParams;
}

interface AlgorithmRequest {
  task_id: string;
  task_callback_url?: string;
  input_params: InputParams;
}

interface AlgorithmResponse {
  task_id: string;
  task_callback_url?: string;
  task_status: TaskStatus;
  task_progress: number;
  task_logs?: string;
  error_message?: string;
  output_params: OutputParams;
  metrics: any[]; // 这里可以根据Chart类型进一步定义
}

interface DRPAInputParams {
  data_flows: Array<Record<string, any>>;
  time_window: number;
  risk_threshold: number;
  sensitivity_weights: {
    data_type: number;
    access_frequency: number;
    user_privilege: number;
    historical_incidents: number;
  };
}

interface WindowAssessment {
  window_id: number;
  start_time: number;
  end_time: number;
  risk_score: number;
  risk_level: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
  flagged_flows: string[];
  mitigation_actions: string[];
}

interface DRPAOutputParams {
  assessments: WindowAssessment[];
  overall_risk_score: number;
  high_risk_patterns: Array<Record<string, any>>;
  recommended_actions: string[];
}

// 添加演化预测算法的输入参数接口
interface EvolutionPredictInputParams {
  historical_data: number[][][];  // 历史时间步的数据，格式为[[[node1,node2,weight], ...], [...]]
  prediction_steps: number;       // 预测未来的时间步数
  window_size: number;            // 用于预测的历史窗口大小
  node_count: number;             // 网络中的节点数量
  prediction_method: string;      // 预测方法，可以是 "linear", "exp", "lstm" 等
}

// 添加演化预测算法的输出参数接口
interface TimePredictionResult {
  time_step: number;              // 时间步
  predicted_edges: number[][];    // 预测的边列表 [[node1,node2,weight], ...]
  confidence_score: number;       // 预测的置信度
  prediction_metrics: Record<string, number>; // 预测的评估指标
}

interface EvolutionPredictOutputParams {
  predictions: TimePredictionResult[];  // 每个预测时间步的结果
  algorithm: string;                    // 算法名称
  parameters: Record<string, any>;      // 算法参数
  overall_accuracy: number;             // 整体预测准确率
}

// 解决 options 选项的类型问题
interface SelectOption {
  value: string;
  label: string;
}

// 修改算法实现
export const EvolutionPredictService: Algorithm = {
  name: "网络演化预测算法",
  description: "基于历史时间序列数据预测未来网络结构演化趋势的算法",
  configOptions: [
    {
      id: "node_count",
      label: "节点数量",
      type: "number",
      defaultValue: 128,
      placeholder: "128"
    },
    {
      id: "window_size",
      label: "历史窗口大小",
      type: "number",
      defaultValue: 5,
      placeholder: "5"
    },
    {
      id: "prediction_steps",
      label: "预测时间步数",
      type: "number",
      defaultValue: 3,
      placeholder: "3"
    },
    {
      id: "prediction_method",
      label: "预测方法",
      type: "select",
      options: ["linear"],
      defaultValue: "linear"
    },
    {
      id: "inputData",
      label: "历史数据",
      type: "textarea",
      placeholder: `请输入JSON格式的历史时间步数据，例如：
[
  [[0, 1, 1], [1, 2, 1], [2, 3, 2]],
  [[0, 1, 2], [1, 2, 1], [0, 3, 1]],
  [[0, 2, 1], [1, 3, 1], [2, 3, 1]]
]`
    }
  ],

  execute: async (config) => {
    try {
      const taskId = `evolution_predict_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      
      let historicalData;
      
      try {
        historicalData = JSON.parse(config.inputData);
      } catch (e) {
        throw new Error("输入数据必须是有效的JSON格式");
      }

      const requestData: AlgorithmRequest = {
        task_id: taskId,
        task_callback_url: "http://172.16.4.151:1122/api/evolution_predict/callback",
        input_params: {
          evolution_predict_params: {
            historical_data: historicalData,
            prediction_steps: Number(config.prediction_steps) || 3,
            window_size: Number(config.window_size) || 5,
            node_count: Number(config.node_count) || 128,
            prediction_method: config.prediction_method || "linear"
          }
        }
      };

      // 创建任务
      const createResponse = await fetch("http://172.16.4.151:1122/api/evolution_predict/create", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(requestData)
      });

      if (!createResponse.ok) {
        const errorData = await createResponse.json();
        throw new Error(errorData.detail || "创建任务失败");
      }

      // 执行任务
      const executeResponse = await fetch(`http://172.16.4.151:1122/api/evolution_predict/execute/${taskId}`, {
        method: "POST"
      });

      if (!executeResponse.ok) {
        const errorData = await executeResponse.json();
        throw new Error(errorData.detail || "执行任务失败");
      }

      // 轮询获取结果
      let result;
      let attempts = 0;
      const maxAttempts = 60;

      while (attempts < maxAttempts) {
        const getResultResponse = await fetch(`http://172.16.4.151:1122/api/evolution_predict/result/${taskId}`);
        
        if (!getResultResponse.ok) {
          const errorData = await getResultResponse.json();
          throw new Error(errorData.detail || "获取结果失败");
        }

        result = await getResultResponse.json();
        
        if (result.task_status === "COMPLETED") {
          break;
        } else if (result.task_status === "FAILED") {
          throw new Error(result.error_message || "任务执行失败");
        }

        await new Promise(resolve => setTimeout(resolve, 1000));
        attempts++;
      }

      if (attempts >= maxAttempts) {
        throw new Error("任务执行超时");
      }

      const outputParams = result.output_params.evolution_predict_results;
      
      // 生成结果摘要
      const resultText = `网络演化预测完成：
算法：${outputParams.algorithm}
整体预测准确率：${(outputParams.overall_accuracy * 100).toFixed(2)}%

预测结果：
${outputParams.predictions.map((pred: TimePredictionResult) => `
时间步 ${pred.time_step}:
- 预测边数: ${pred.predicted_edges.length}
- 置信度: ${(pred.confidence_score * 100).toFixed(2)}%
- 评估指标:
  ${Object.entries(pred.prediction_metrics).map(([key, value]: [string, number]) => `${key}: ${value.toFixed(4)}`).join('\n  ')}
`).join('\n')}`;

      return {
        result: resultText,
        steps: [],
        executionTime: 0,
        details: {
          predictions: outputParams.predictions,
          overall_accuracy: outputParams.overall_accuracy,
          algorithm: outputParams.algorithm,
          parameters: outputParams.parameters
        }
      };
    } catch (e: any) {
      console.error("网络演化预测算法执行出错:", e);
      throw e;
    }
  }
}; 